﻿
using Jmit.Common;
using Jmit.Deyi.Job;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace Jmit.Deyi.AutoTask.DataSync
{
    public partial class Form1 : Form
    {

        public bool isRunning = false;          // 定时任务是否运行
        public static bool isSelectedJob1 = false;     // 是否允许执行任务1
        public static bool isSelectedJob2 = false;     // 是否允许执行任务2


        public static string g_newfromname = ""; // 同步新企业名称

        public Form1()
        {

            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            initConfig();

            Start();
            this.notifyIcon1.Visible = true; //在通知区显示Form的Icon
        }


        //private DeyiConfig deyiConfig = new DeyiConfig();

        private void initConfig()
        {

            AppConfigManager.LoadConfig();

            this.tb_hour.Value = int.Parse(AppConfigManager.appConfig.hour);
            this.tb_minute.Value = int.Parse(AppConfigManager.appConfig.minute);

            string msg = "";
            if (AppManage.IsNewAccount())
            {
                msg = "(新账号：" + AppManage.newFromName + ")";
            }
            this.toolStripStatusLabel1.Text =  AppManage.appVersion + msg;
            
            LogBLL.log("是否新开账号：" + AppManage.IsNewAccount());
            LogBLL.log("版本号：" + AppManage.appVersion + msg);

        }



        private void btnStart_Click(object sender, EventArgs e)
        {
            Start();

            // test
            /*string from_name = "8001B5 丽珠集团23";
            string from_id = AppManage.GetFromDict(from_name);
            string abc = "";*/

        }

        private static JobStart jobStart;
        private void Start()
        {
            //
            isSelectedJob1 = checkBox1.Checked;
            isSelectedJob2 = checkBox2.Checked;


            if (!isRunning)
            {
                saveConfig();
                UpdateUI(true);
                MainAsyncStart();

            }
            else
            {
                UpdateUI(false);
                MainAsyncShutdown();
            }

        }

        private void UpdateUI(bool state)
        {
            if (state)
            {
                isRunning = true;
                label1.Text = "运行中...";
                label1.ForeColor = Color.Green;

                btnStart.Text = "停止";

                groupBox1.Enabled = false;
                groupBox3.Enabled = false;
            }
            else
            {
                isRunning = false;
                label1.Text = "停止";
                label1.ForeColor = Color.Red;

                btnStart.Text = "启动";
                groupBox1.Enabled = true;
                groupBox3.Enabled = true;
            }

        }

        #region 定时任务
        static async Task TestAsyncStart()
        {

            jobStart = new JobStart();
            jobStart.Start();
        }

        static async Task TestAsyncShutdown()
        {
            jobStart.Close();
        }

        // 任务调度
        public static StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
        static async Task MainAsyncStart()
        {

            //创建一个Scheduler任务调度容器
            var scheduler = await schedulerFactory.GetScheduler();
            await scheduler.Start();
            Console.WriteLine($"任务调度器已启动");
            LogBLL.log("任务开启");

            //创建作业和触发器

            //指定具体执行的任务Job
            var jobDetail = JobBuilder.Create<DSHJob>().Build();
            //设置触发条件为五秒执行一次
            var trigger = TriggerBuilder.Create()
                                        .WithCronSchedule($"0 {AppConfigManager.appConfig.minute} {AppConfigManager.appConfig.hour} * * ?") // 每日执行
                                        //.WithCronSchedule($"0 */1 * * * ?") // 每5分钟执行
                                        //.WithCronSchedule($"0/5 * * * * ?") // 每5分钟执行
                                        .Build();





            //指定具体执行的任务Job2
            var jobDetail2 = JobBuilder.Create<TimingJob2>().Build();
            var trigger2 = TriggerBuilder.Create()
                                        //.WithCronSchedule($"0 {AppConfigManager.appConfig.minute} {AppConfigManager.appConfig.hour} * * ?") // 每日执行
                                        //.WithCronSchedule($"0 */1 * * * ?") // 每5分钟执行
                                        .WithCronSchedule($"*/{AppConfigManager.appConfig.interval} * * * * ?") // 每5分钟执行
                                        .Build();



            //把策略和任务放入到Scheduler
            if (isSelectedJob1)
            {
                await scheduler.ScheduleJob(jobDetail, trigger);
            }

            /*if (isSelectedJob2)
            {
                await scheduler.ScheduleJob(jobDetail2, trigger2);
            }*/

            //执行任务
            await scheduler.Start();
        }

        static async Task MainAsyncShutdown()
        {
            //创建一个Scheduler任务调度容器
            var scheduler = await schedulerFactory.GetScheduler();
            if(scheduler != null)
            {
                await scheduler.Shutdown();
                Console.WriteLine($"任务调度器已关闭");
                LogBLL.log("任务关闭");
            }
            


        }

        #endregion


        #region 托盘最小化和退出



        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.Hide();
            if (!isClose)
            {
                this.WindowState = FormWindowState.Minimized;
                notifyIcon1.BalloonTipTitle = this.Text + "提示";
                notifyIcon1.BalloonTipText = "程序将在后台继续为您服务...";
                notifyIcon1.ShowBalloonTip(5000);
                e.Cancel = true;
            }
        }

        bool isClose = false;

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show();
            }
        }


        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

        /// <summary>
        /// 显示窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }

        /// <summary>
        /// 退出服务程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("现在退出程序吗？", "确认退出", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            if (dr == DialogResult.Yes)
            {
                //try { Log.Info(G_VAR.LogPATH, "程序退出", "退出程序完成"); }
                //catch { ;}
                //Log.WriterLog("退出", "程序被强制关闭.");

                //   在应用程序关闭时运行的代码
                /*var scheduler = schedulerFactory.GetScheduler();
                if (scheduler != null)
                {
                    scheduler.Shutdown(true);
                }*/
                MainAsyncShutdown();

                isClose = true;
                Application.Exit();
            }
        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            saveConfig();

            MessageBox.Show(this, "保存成功", "提示");
        }

        private void saveConfig()
        {
            AppConfigManager.appConfig.hour = this.tb_hour.Value.ToString();
            AppConfigManager.appConfig.minute = this.tb_minute.Value.ToString();
            AppConfigManager.SaveConfig(AppConfigManager.appConfig);
            AppConfigManager.LoadConfig();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            isSelectedJob1 = checkBox1.Checked;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            isSelectedJob2 = checkBox2.Checked;

        }


        // 同步新企业数据

        private void btn_add_newfrom_Click(object sender, EventArgs e)
        {
            g_newfromname = tb_newfrom.Text;
            tb_newfrom.Text = "";
            //Console.WriteLine($"按钮点击同步新企业数据 企业：{g_newfromname}，Time：{DateTime.Now}");

            // 注册立即执行的任务，但不立即触发
            if(g_newfromname != "")
            {
                MainAsyncRun();
            }
            


        }

        static async Task MainAsyncRun()
        {
            // 创建一个Scheduler任务调度容器
            var scheduler = await schedulerFactory.GetScheduler();
            LogBLL.log("立即同步新企业数据 " + g_newfromname);


            //立即执行指定任务
            //var jobDetail = JobBuilder.Create<TestJob1>().Build();    // 测试job
            var jobDetail = JobBuilder.Create<DSHJob>().Build();        // deyi数据同步任务

            ITrigger trigger = TriggerBuilder.Create()
              .WithIdentity("firstTrigger", "group1")
              .StartNow() // 立即执行
              .Build();



            await scheduler.ScheduleJob(jobDetail, trigger);

            Console.WriteLine($"立即执行3");

        }
    }
}
